<template>
	<div style="background-color: #f04e7c;">
		<!-- 加载状态 -->
		<div v-if="loading" class="cPage">
			<div style="text-align: center; padding: 50px;">
				<div style="font-size: 16px; color: #666;">加载中...</div>
			</div>
		</div>
		
		<!-- 错误状态 -->
		<div v-else-if="detail === null" class="cPage">
			<div style="text-align: center; padding: 50px;">
				<div style="font-size: 16px; color: #666;">商品信息不存在或已下架</div>
				<div style="margin-top: 20px;">
					<button @click="goBack" style="background-color: #f04e7c; color: white; border: none; padding: 10px 20px; border-radius: 5px;">返回首页</button>
				</div>
			</div>
		</div>
		
		<!-- 正常显示 -->
		<div v-else>
			<div class="cPage">
				<div class="rowStart">
					<image :src="detail.coverImg.url" style="width: 100px;height: 135px;border-radius: 8px;" />
					<div style="flex:1;margin-left: 16px;" class="colBetween">
						<div>
							<div style="font-size: 16px;font-weight: 400;line-height: 32px;">{{detail.name}}</div>
							<div style="font-size: 16px;font-weight: 500; color:#deb74e;margin-top: 8px;">
								{{detail.categoryId.length > 0 ? detail.categoryId[0].name : ""}}</div>
						</div>
						<div style="font-size: 18px;font-weight: 500;color: #d13d62;">￥{{getMoney(detail.gradeMoneys)}}
						</div>
					</div>
				</div>
				<div style="margin-top: 20px;border-bottom: solid 1px #f2f2f2;padding-bottom: 12px;">
					<div style="font-size: 14px;font-weight: 500">{{getTime(detail.sessionTimes)}}</div>
					<div style="font-size: 14px;color: #999999;margin-top: 4px;">约{{detail.duration}}分钟（以现场为准）</div>
				</div>
				<div style="margin-top: 12px;border-bottom: solid 1px #f2f2f2;padding-bottom: 12px;" class="rowBetween" v-if="detail.city.length > 0 && detail.theaterName.length > 0">
					<div>
						<div style="font-size: 14px;font-weight: 500">{{detail.city}} | {{detail.theaterName}}</div>
						<!-- <div style="font-size: 14px;color: #999999;margin-top: 4px;">{{detail.city}}<span style="color: #999999;"> | </span>{{detail.theaterName}}</div> -->
						<div v-if="detail.theaterId.length > 0" style="font-size: 14px;color: #999999;margin-top: 4px;">
							{{detail.theaterId[0].addr}}</div>
					</div>
					<div style="align-self: center;font-size: 12px;color: blue" @click="onCopyAddress">复制地址</div>
				</div>
				<mp-html :content="detail.introduction"></mp-html>
			</div>
			<div style="width: 100%;height: 60px"></div>
			<div class="cFixBottom rowEnd">
				<!-- #ifdef MP-WEIXIN -->
				<!-- 小程序分享 -->
				<button id="idShare" open-type="share" hover-class='none' class="cShareButton" size="mini">分享</button>
				<!-- #endif -->

				<!-- #ifndef MP-WEIXIN -->
				<!-- 非小程序分享 -->
				<button id="idShare" hover-class='none' class="cShareButton" size="mini" @click="onShare">分享</button>
				<!-- #endif -->

				<div class="cChooseSite" @click="onChooseSite">优惠下单</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
	import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
	import { ref, computed, onMounted } from "vue";
	import { onReachBottom, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
	import { onLoad } from "@dcloudio/uni-app";
	import DbUtil from "@/utils/DbUtil";
	import StrUtil from "@/utils/StrUtils.js";
	import { gzhShare, shareFriend, shareTimeline } from "@/utils/WxGzhUtil";
	
	
	const sxf_theater = uniCloud.importObject("sxf-theater");
	
	
	//分享
	onShareAppMessage((options) => {
		console.log("onShareAppMessage.options:", options);

		// 检查是否有商品详情数据
		if (detail.value === null) {
			return {
				title: "向您分享小程序：" + getApp().globalData.appName,
				path: "/pages/launch/welcomeMp?page=main_page&tab=MainPage",
			}
		}

		let share =  {
			title: "向您分享" + detail.value.name,
			path: "/pages/launch/welcomeMp" +
				"?page=main_page&tab=MainPage" +  // tab: 首页-MainPage，全友圈-FriendList，活动-ActivityList，通讯录-BusinessCard，我的-My,
				"&shareUserId=" + getApp().globalData.curUserId +
				"&detailId=" + detail.value._id +
				"&shareOpenId=" + getApp().globalData.curOpenId,
			imageUrl: detail.value.coverImg.url,
		}
		
		console.log(share.path, "xzzz")
		
		return share
	})
	
	// 分享朋友圈
	onShareTimeline(() => {
		console.log("onShareTimeline");
	
		// 检查是否有商品详情数据
		if (detail.value === null) {
			return {
				title: "向您分享小程序：" + getApp().globalData.appName,
				path: "/pages/launch/welcomeMp",
				query: "page=main_page&tab=MainPage",
			}
		}

		let share =  {
			title: "向您分享" + detail.value.name,
			path: "/pages/launch/welcomeMp",
			query: "page=main_page&tab=MainPage" +  // tab: 首页-MainPage，全友圈-FriendList，活动-ActivityList，通讯录-BusinessCard，我的-My,
				"&shareUserId=" + getApp().globalData.curUserId +
				"&shareOpenId=" + getApp().globalData.curOpenId +
				"&detailId=" + detail.value._id,
			imageUrl: detail.value.coverImg.url,
		}
		
		console.log("朋友圈分享path:", share.path)
		console.log("朋友圈分享query:", share.query)
		return share
	})

	let detail = ref(null)
	let loading = ref(true)
	let shareInfo = ref({})
	
	const goBack = () => {
		uni.switchTab({
			url: "/pages/ticker/list"
		})
	}
	
	onLoad(async (options) => {
		console.log("------detail onLoad")
		console.log("接收到的参数:", options)
		
		// 先正常加载详情页面
		await processDetailPage(options)
		
		// 加载完成后，检查是否需要跳转到welcomeMp
		await processWelcomeMp(options)
	})
	
	const processDetailPage = async (options) => {
		// 处理不同的参数名：id 或 detailId
		let productId = options.id || options.detailId
		console.log("商品ID:", productId)
		
		if (!productId) {
			console.error("没有找到商品ID")
			detail.value = null
			loading.value = false
			return
		}
		
		try {
			console.log("开始查询商品详情...")
			detail.value = await DbUtil.getInstance("ndp-theater-product, ndp-theater-info, ndp-theater-product-category").getById(productId)
			console.log("detail:", detail.value)
		} catch (error) {
			console.error("获取商品详情失败:", error)
			detail.value = null
		} finally {
			loading.value = false
		}

		// 只有在成功获取到商品详情时才设置分享信息
		if (detail.value !== null) {
			// https://tcb-ndt2n24tbmyeiti-4c1c5ac10cb1.service.tcloudbase.com  // 云函数url化的
			const shareLinkUrl = 'https://www.niudai-sy.com/sxf_theater/welcome' +  // 用纽带的透传
				"?page=main_page&tab=MainPage" +  // tab: 首页-MainPage，全友圈-FriendList，活动-ActivityList，通讯录-BusinessCard，我的-My,
				"&shareUserId=" + getApp().globalData.curUserId +
				"&detailId=" + detail.value._id +
				"&shareOpenId=" + getApp().globalData.curOpenId;
				
			const shareImageUrl = detail.value.coverImg.url;
			
			console.log("shareUrl", shareLinkUrl)

			shareInfo.value = {
				title: "向您分享" + detail.value.name,
				desc: "邀请您亲临现场感受舞台剧魅力",
				link: shareLinkUrl,
				imgUrl: shareImageUrl
			}
			gzhShare({
				isShowMenu: true, // 显示菜单
				shareInfo: shareInfo.value
			});
			wx.showShareMenu({
				menus: ['shareAppMessage', 'shareTimeline'],// 需要显示的转发按钮名称列表.合法值包含 "shareAppMessage"、"shareTimeline"
				success(res) {
					console.log(res);
				},
				fail(e) {
					console.log(e);
				}
			});
		}
		
		// 增加浏览总次数
		if (detail.value !== null) {
			const res = await sxf_theater.addProductViewNum({
				productId: detail.value._id, 
				productName: detail.value.name,
				userId: getApp().globalData.curUserId
			});
		}
	}

	const processWelcomeMp = async (options) => {
		console.log("processWelcomeMp")
		
		try {
			if (options.page === "main_page" && options.tab === "MainPage") {
				console.log("检测到分享参数，准备跳转到welcomeMp进行完整处理")
				
				// 延迟跳转，让用户先看到内容
				setTimeout(() => {
					try {
						console.log("开始执行跳转到welcomeMp")
						// 先尝试redirectTo，如果失败再尝试reLaunch
						uni.redirectTo({
							url: "/pages/launch/welcomeMp" + 
							"?page=" + options.page + 
							"&tab=" + options.tab + 
							"&shareUserId=" + options.shareUserId + 
							"&shareOpenId=" + options.shareOpenId + 
							"&detailId=" + options.detailId,
							success: () => {
								console.log("redirectTo成功")
							},
							fail: (err) => {
								console.log("redirectTo失败，尝试reLaunch:", err)
								// 如果redirectTo失败，尝试reLaunch
								uni.reLaunch({
									url: "/pages/launch/welcomeMp" + 
									"?page=" + options.page + 
									"&tab=" + options.tab + 
									"&shareUserId=" + options.shareUserId + 
									"&shareOpenId=" + options.shareOpenId + 
									"&detailId=" + options.detailId
								})
							}
						})
					} catch(ex) {
						console.error("跳转welcomeMp失败:", ex)
					}
				}, 500) // 延迟0.5秒，让用户看到内容
			}
		} catch(ex) {
			console.error("跳转welcomeMp失败:", ex)
		}
	}

	const getMoney = computed(() => (moneys : any[]) => {
		// return moneys[0] + " - " + moneys[moneys.length - 1]
		if (!moneys || moneys.length === 0) {
			return '--'
		}
		// let money1 = moneys[0] + ''
		// 从moneys中取最小的
		let money1 = Math.min(...moneys) + ''
		if (money1.endsWith(".00")) {
			money1 = money1.substring(0, money1.length - 3)
		}
		// let money2 = moneys[moneys.length - 1] + ''
		// 从moneys中取最大的
		let money2 = Math.max(...moneys) + ''
		if (money2.endsWith(".00")) {
			money2 = money2.substring(0, money2.length - 3)
		}
		return money1 + " - " + money2
	})

	const getTime = computed(() => (_times : any[string]) => {
		if (!_times || _times.length === 0) {
			// console.log("-------000")
			return '下单后时间可以商议'
		}
		if (_times.length == 1) {
			if (!_times[0]) return ''
			return _times[0].substring(0, 10).replaceAll('-', '.') + " " + StrUtil.getWeek(_times[0]) + " " + _times[0].substring(11, 16)
		} else {
			let start = _times[0]
			let end = _times[_times.length - 1]
			if (!start || !end) return ''
			// 从times中截取时间(时:分)来拼装，如：10:00/14:00/16:00
			let hourMinusTimes = []
			for (var i = 0; i < _times.length; i++) {
				const tmpHourMinusStr = _times[i].substring(11, 16)
				if (!hourMinusTimes.includes(tmpHourMinusStr)) {
					hourMinusTimes.push(tmpHourMinusStr)
				}
			}
			let hourMinusTimesStr = ""
			if (hourMinusTimes.length > 0) {
				hourMinusTimesStr = hourMinusTimes.join("/")
			}
			// if (start.substring(0, 4) == end.substring(0, 4)) {
			// 	return start.substring(0, 10).replaceAll('-', '.') + " - " + end.substring(0, 10).replaceAll('-', '.')
			// }
			return start.substring(0, 10).replaceAll('-', '.') + " - " + end.substring(0, 10).replaceAll('-', '.') + " " + hourMinusTimesStr
		}
		return '下单后时间可以商议'
	})

	const onChooseSite = () => {
		if (detail.value === null) {
			uni.showToast({
				title: '商品信息不存在',
				icon: 'error'
			})
			return
		}
		
		let theSessionTimes = ['下单后时间可以商议']
		if (detail.value.sessionTimes.length > 0) {
			theSessionTimes = detail.value.sessionTimes
		}
		let json = {
			id: detail.value._id,
			gradeMoneys: detail.value.gradeMoneys,
			sessionTimes: theSessionTimes,
			name: detail.value.name,
			coverImg: detail.value.coverImg.url,
			channelCommissionAmount: detail.value.channelCommissionAmount,  // 配置的渠道佣金金额（分）
			commissionAmounts: detail.value.commissionAmounts, // 票档与渠道佣金（元）
			city: detail.value.city,
			theaterName: detail.value.theaterName,
			seatImg: detail.value.theaterId.length > 0 ? detail.value.theaterId[0].seatImg.url : "", // 座位图
			categoryName: detail.value.categoryId.length > 0 ? detail.value.categoryId[0].name : "", // 分类名称
			tickectType: detail.value.tickectType, // 票据类型（1-实体票，2-电子票）
		}
		uni.navigateTo({
			url: "/pages/ticker/choosesite?row=" + encodeURIComponent(JSON.stringify(json))
		})
	}

	const onShare = () => {
		console.log("onShare");
		uni.showToast({
			title: '请点击右上角"..."进行分享',
			icon: "none",
			duration: 2000
		});
	}

	// 复制地址
	const onCopyAddress = () => {
		if (detail.value === null || detail.value.theaterId.length === 0) {
			uni.showToast({
				title: '地址信息不存在',
				icon: 'error'
			})
			return
		}
		
		if (detail.value.theaterId.length > 0) {
			// #ifdef MP-WEIXIN
			// 如果是小程序
			uni.setClipboardData({
				data: detail.value.theaterId[0].addr,
				success: () => {
					uni.showToast({
						title: "复制成功",
						icon: "success"
					});
				}, fail: () => {
					uni.showToast({
						title: "复制失败",
						icon: "error"
					});
				}
			});
			// #endif

			// #ifndef MP-WEIXIN
			// 如果不是小程序
			// 创建临时input元素
			const input = document.createElement('input');
			input.value = detail.value.theaterId[0].addr;
			// 添加到页面并选中内容
			document.body.appendChild(input);
			input.select();
			// 执行复制操作
			const res = document.execCommand('copy');
			// 清除临时input元素
			document.body.removeChild(input);

			if (res) {
				uni.showToast({
					title: "复制成功",
					icon: "success"
				});
			} else {
				uni.showToast({
					title: "复制失败",
					icon: "error"
				});
			}
			// #endif
		}
	}
</script>

<style lang="scss" scoped>
	.cPage {
		border-top-left-radius: 16px;
		border-top-right-radius: 16px;
		background: white;
		padding: 16px;
	}

	.cFixBottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 60px;
		border-top: solid 1px #f2f2f2;
		background-color: white;
	}

	.cShareButton {
		width: 80px;
		line-height: 38px;
		color: #f04e7c;
		font-size: 16px;
		background-color: white;
		border: solid 1px #f04e7c;
		border-radius: 19px;
		align-self: center;
	}

	.cChooseSite {
		width: 180px;
		line-height: 38px;
		background-color: #f04e7c;
		color: white;
		font-size: 16px;
		font-weight: 500;
		border-radius: 19px;
		align-self: center;
		text-align: center;
		margin-right: 16px;
	}
</style>